<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="800" @ok="handleSubmit">
    <BasicForm @register="registerForm" name="ZhibiaobiaoForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive, onMounted } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { formSchema } from '../Zhibiaobiao.data';
import { saveOrUpdate } from '../Zhibiaobiao.api';
import { useMessage } from '/@/hooks/web/useMessage';
import { getDateByPicker } from '/@/utils';
import { defHttp } from '/@/utils/http/axios';

const { createMessage } = useMessage();
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
const isDetail = ref(false);

// 表单配置
const [registerForm, { setProps, resetFields, setFieldsValue, validate, scrollToField }] = useForm({
  labelWidth: 150,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 24 },
});

// 弹窗注册
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  await resetFields();
  setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter });
  isUpdate.value = !!data?.isUpdate;
  isDetail.value = !!data?.showFooter;
  if (unref(isUpdate)) {
    console.log('编辑数据：', data.record);
    await setFieldsValue({ ...data.record });
  }
  setProps({ disabled: !data?.showFooter });
});

// 日期处理配置
const fieldPickers = reactive({});

// 标题
const title = computed(() => (!unref(isUpdate) ? '新增' : !unref(isDetail) ? '详情' : '编辑'));

//加载“配合部门”选项
onMounted(async () => {
  try {
    const res = await defHttp.get({ url: '/zhibiaobiao/zhibiaobiao/peihe' });
    const data = res?.result ?? res;

    const peiheField = formSchema.find((item) => item.field === 'peihebumen');
    if (peiheField) {
      peiheField.componentProps.options = data.map((item) => ({
        label: item.departName,
        value: item.id,
      }));
      console.log('已加载配合部门：', peiheField.componentProps.options);
    }
  } catch (err) {
  } catch (err) {
    console.error('加载配合部门失败：', err);
  }
});

// 表单提交
async function handleSubmit() {
  try {
    let values = await validate();
    changeDateValue(values);
    setModalProps({ confirmLoading: true });
    await saveOrUpdate(values, isUpdate.value);
    closeModal();
    emit('success');
  } catch ({ errorFields }) {
    if (errorFields) {
      const firstField = errorFields[0];
      if (firstField) {
        scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
      }
    }
    return Promise.reject(errorFields);
  } finally {
    setModalProps({ confirmLoading: false });
  }
}

// 日期格式转换
const changeDateValue = (formData) => {
  if (formData && fieldPickers) {
    for (let key in fieldPickers) {
      if (formData[key]) {
        formData[key] = getDateByPicker(formData[key], fieldPickers[key]);
      }
    }
  }
};
</script>

<style lang="less" scoped>
:deep(.ant-input-number),
:deep(.ant-calendar-picker) {
  width: 100%;
}
</style>
